package com.jt.controller;

import com.jt.mapper.FileMapper;
import com.jt.pojo.User;
import com.jt.service.FileService;
import com.jt.vo.ImagedVO;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private FileService fileService;

    @RequestMapping("/upload")
    public User upload(ImagedVO imagedVO) throws IOException, InterruptedException {
        MultipartFile file=imagedVO.getFile();
        String fileName = file.getOriginalFilename();
        String dirPath = "E:/nodejs/vueproject/aj-cloud/src/assets/images/";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
//        String filePath = "E:/nodejs/vueproject/aj/src/assets/images/" + fileName;
        //4.实现文件上传
        String uuid= UUID.randomUUID().toString().replace("-","");
        int index=fileName.lastIndexOf(".");
        String fileType=fileName.substring(index);
        String realFileName=uuid+fileType;
        String filePath=dirPath+realFileName;
        file.transferTo(new File(filePath));

        Integer id=imagedVO.getId();
        fileMapper.setImages(id,realFileName);
//        Thread.sleep(1000);
        return fileMapper.getUser(imagedVO.getId());

    }

    @RequestMapping("/getUser")
    public User getUser(Integer id){
        return fileMapper.getUser(id);
    }


    @RequestMapping("/addUpload")
    public SysResult addUpload(@RequestPart(value = "file") MultipartFile file){
        String imageName=fileService.upload(file);
        if(imageName==null){
            return SysResult.fail();
        }
        return SysResult.success(imageName);
//        return SysResult.success(null);
    }

}
